package twidledee.server;

import java.util.List;
import java.util.logging.Logger;

import javax.jdo.JDOHelper;
import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;
import javax.jdo.Query;

import twidledee.client.RegisterUserService;
import twidledee.client.User;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

@SuppressWarnings("serial")
public class RegisterUserServiceImpl extends RemoteServiceServlet implements RegisterUserService {
	
	private static final Logger LOG = Logger.getLogger(RegisterUserServiceImpl.class.getName());
	private static final PersistenceManagerFactory PMF = JDOHelper.getPersistenceManagerFactory("transactions-optional");
	
	
	@Override
	public boolean registerUser(User user) {
		if (checkUserExists(user)) return false;
		
		PersistenceManager pm = getPersistenceManager();
		pm.makePersistent(user);
		
		return true;
	}
	
	public boolean deregisterUser(User user) {
		//TODO
		return false;
	}
	
	public boolean checkUserExists(User user){
		PersistenceManager pm = getPersistenceManager();
		Query query = pm.newQuery(User.class, "userName == u");
		query.declareParameters("twidledee.client.User u");
		List<User> users = (List<User>) query.execute(user.getUserName());
		
		return !users.isEmpty();
	}
	
	private PersistenceManager getPersistenceManager() {
	    return PMF.getPersistenceManager();
	}

}
